<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, h } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import type { PatrolInspectionType } from '@/api/linePatrol/type'
import DeptApi from '@/api/dept'
// import * as XLSX from "xlsx";
import PipnentInfoApi from '@/api/equip/pipnet'
import EditPipeLine from './components/EditPipeLine.vue'
import { useI18n } from 'vue-i18n'
import { BaseButton } from '@/components/Button'
import { ElTag } from 'element-plus'
import { useDictStore } from '@/store/modules/dictData'
import { useGISStore } from '@/store/modules/gis'
import { useDeptStore } from '@/store/modules/dept'
const DictStore = useDictStore()
const { t } = useI18n()
const DeptStore = useDeptStore()
const GISStore = useGISStore()
if (DeptStore.DeptListTypeDetail.length == 0) {
  DeptStore.setFacilityTypeDetail()
}
if (GISStore.getPnLedgerList.length == 0) {
  GISStore.setPnLedgerList() //获取管网信息
}
DictStore.setDict('pipe_material') //材质字典
DictStore.setDict('pipe_state') //状态字典
DictStore.setDict('pipe_line_type') //状态字典
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    fixed: 'left'
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    fixed: 'left',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'dataSource',
    label: t('数据来源'),
    width: 100,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'pipeLineName',
    label: t('管线名称'),
    width: 100,
    form: {
      colProps: {
        span: 13
      }
    },
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '管线名称'
      }
    }
  },
  {
    field: 'pipeState',
    label: t('使用状态'),
    width: 100,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.pipe_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => item.dictLabel)
        }
      })
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '使用状态',
        options: DictStore.$state.pipe_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: DictStore.$state.pipe_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'pipeLineType',
    label: t('管线类型'),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.pipe_line_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '管线类型',
        options: DictStore.$state.pipe_line_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: DictStore.$state.pipe_line_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'pressure',
    label: t('压力值'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'pipeLineNo',
    label: t('管线编码'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'buriedWay',
    label: t('埋设方式'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'material',
    label: t('材质'),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.pipe_material?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: DictStore.$state.pipe_material?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'deptId',
    label: t('责任部门'),
    width: 150,
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      if (cellValue !== undefined && cellValue) {
        return DeptStore.getDeptName(cellValue)[0]?.deptName
      }
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: async () => {
        const res = await DeptApi.GetDeptListTree()
        return res.data
      }
    }
  },
  {
    field: 'pipeUuid',
    label: t('所属管网'),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return GISStore.getPnLedgerList.map((item) => {
        if (item.uuid == cellValue) {
          return item.pnName
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 12
      },
      componentProps: {
        options: GISStore.getPnLedgerList.map((item) => {
          return {
            label: item.pnName,
            value: item.uuid
          }
        })
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'pipeDiameter',
    label: t('管径'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'pipeLong',
    label: '管长（m）',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'pipeStore',
    label: '管存（Nm³）',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'startHeight',
    label: '起点高程',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'endHeight',
    label: '终点高程',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'startDepth',
    label: '起点埋深',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'endDepth',
    label: '终点埋深',
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row)}>
                修改
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                删除
              </span>
            </>
          )
        }
      }
    }
  }
])
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const i = await PipnentInfoApi.GetPipeLineList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await PipnentInfoApi.DeletPipeLine(unref(ids)[0])
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const delLoading = ref(false)
const saveLoading = ref(false)
const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const currentRow = ref<PatrolInspectionType>({})
//表格操作
const action = (row: PatrolInspectionType) => {
  currentRow.value = row
  dialogVisible.value = true
}
const EditCofigRef = ref()
const save = async () => {
  const write = unref(EditCofigRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    res.value = await PipnentInfoApi.EditPipeLine(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
//巡检任务表格导出excel
const ExportTableData = async () => {
  const i = await PipnentInfoApi.GetPipeLineList({
    pageNum: 1,
    pageSize: total.value,
    ...unref(searchParams)
  })
  console.log(i.rows)
  // var workbook = XLSX.utils.book_new();
  //在table上建立的id属性
  // var ws1 = XLSX.utils.table_to_sheet(document.getElementById("table"));
  // XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
  // XLSX.writeFile(workbook, `巡检任务.xlsx`);
}
</script>
<template>
  <ContentWrap>
    <BaseButton size="small" type="primary" @click="ExportTableData">
      <Icon icon="ep:download" :size="12" />导出</BaseButton
    >
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      id="table"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="uuid"
      :loading="loading"
      :pagination="{
        total: total,
        pageSize: pageSize
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisible" title="任务详情">
    <EditPipeLine
      ref="EditCofigRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save"> 提交 </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
:deep(.el-form) {
  float: right;
}
</style>
